# -*- coding: utf-8 -*-
from app import app, db
from flask import render_template, request, redirect, url_for, abort, g
from flask_login import login_user, logout_user
from login.forms import LoginForm
from models import Post

from entries.blueprint import posts
from reader.blueprint import reader
from image.blueprint import image

app.register_blueprint(posts, url_prefix='/post')
app.register_blueprint(reader, url_prefix='/reader')
app.register_blueprint(image, url_prefix='/image')


@app.route('/')
def index():
    post = Post.query.order_by(Post.create_time.desc()).first()
    return render_template('index.html', post=post)


@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        form = LoginForm(request.form)
        if form.validate():
            login_user(form.user, remember=form.remember_me.data)
            return redirect(request.args.get('next') or url_for('post.index'))
    else:
        form = LoginForm()
    return render_template('login.html', form=form)


@app.route('/logout')
def logout():
    logout_user()
    return redirect(request.args.get('next') or url_for('index'))


@app.route('/about')
def about():
    return render_template('about.html')


@app.route("/show/<int:id>")
def show(id):
    p = Post.query.get(id)
    if p is None or p is False:
        abort(404)
    if g.user.is_authenticated is False:
        p.read_count += 1
    db.session.add(p)
    db.session.commit()
    return render_template('show.html', post=p)


@app.route("/scroll")
def scroll():
    return render_template("scroll.html")
